import Vue from 'vue';
import {
	BASE_URL,
	WX_APPID,
} from './config.js';


import {
	GetBucketToken,
	GetPointOrderPay,
	GetWeiXinPay,
	GetNewOrderList
} from 'api/index';
import log from './log';
const qiniuUploader = require('../util/qiniuUploader.js')

export const uploadMixin = {
	data() {
		return {
			// imageURL:'',
			//    uptoken:''
		}
	},
	methods: {
		uploadImg() {
			return new Promise((resolve, reject) => {
				this.chooseImg().then(tempFilePaths => {
					this.uploadFile(tempFilePaths[0]).then(res => {
						resolve(res);
					}).catch(err => {
						reject(err);
					})
				})
			})
		},
		chooseImg() {
			return new Promise((resolve, reject) => {
				wx.chooseImage({
					success(file) {
						console.log(file);
						const tempFilePaths = file.tempFilePaths
						resolve(tempFilePaths);
					},
					fail(err) {
						wx.hideLoading()
						reject(err);
					}
				})
			});
		},
		uploadFile(path) {


			return new Promise((resolve, reject) => {
				wx.showLoading()
				GetBucketToken().then(res1 => {
					// this.uptoken=;
					qiniuUploader.upload(path, (res) => {
						wx.hideLoading()
						// this.setData({
						// 	'imageURL': res.imageURL,
						// });
						// this.imageURL=res.imageURL;
						resolve(res.imageURL)
						// console.log("666:==>"+JSON.stringify(res));
					}, (error) => {
						wx.hideLoading()
					}, {
						region: 'SCN', //华南
						domain: res1.qiniuhostname, // 
						key: 'st/'+new Date().getFullYear()+"/"+(new Date().getMonth()+1)+"/"
						+new Date().getDate()+"/"+new Date().getTime() + "_" + Math.random().toFixed(6).slice(-
							6) + ".jpg", // 上传到七牛云图片就是这名字了
						// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
						uptoken: res1.token, // 由其他程序生成七牛 uptoken
						// uptokenURL: '存储空间所在区域', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
						// uptokenFunc: function() {
						// 	return '[yourTokenString]';
						// }
					}, (res) => {
						console.log('上传进度', res.progress)
						console.log('已经上传的数据长度', res.totalBytesSent)
						console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
					}, () => {
						// 取消上传
					}, () => {
						// `before` 上传前执行的操作
					});

				})
				// let url = BASE_URL + 'Upload/ImgUpload';
				// wx.uploadFile({
				// 	url: url,
				// 	filePath: path,
				// 	name: 'file',
				// 	header: {
				// 		'content-type': 'multipart/form-data',
				// 		'AuthToken': wx.getStorageSync('token').token
				// 	},
				// 	success(res) {
				// 		wx.hideLoading();
				// 		// let d = JSON.parse(res.data);
				// 		// console.log(d);
				// 		resolve(res);
				// 		// if (d.return_code == '0') {
				// 		// 	let obj = d.return_data;
				// 		// 	// 补全字段
				// 		// 	if (!obj.Id) obj.Id = '';
				// 		// 	if (!obj.ImgUrl) obj.ImgUrl = obj.Url;
				// 		// 	if (!obj.ImgKey) obj.ImgKey = obj.Key;
				// 		// 	wx.hideLoading()
				// 		// 	resolve(obj);
				// 		// } else {
				// 		// 	wx.hideLoading()
				// 		// 	reject('上传失败!');
				// 		// }
				// 	},
				// 	fail(err) {
				// 		wx.hideLoading()
				// 		reject(err);
				// 	}
				// })
			});
		}
	}
}


export const CopyCallMixin = {
	methods: {
		callOrCopy(m) {
			console.log(m);
			if (m) {
				wx.showActionSheet({
					alertText: m,
					itemList: ['呼叫', '复制号码'],
					success: (res) => {
						if (res.tapIndex == 0) {
							wx.makePhoneCall({
								phoneNumber: m
							})
						} else {
							this.copyAction(m)
						}
					}
				})
			}
		},
		copyAction(data) {
			wx.setClipboardData({
				data,
				success() {
					getApp().showToast({
						title: '复制成功',
						icon: 'success'
					})
				}
			})
		},
	}
}



export const LocateMixin = {
	methods: {
		navigateLocation() {
			if (!this.info.TXLat || !this.info.TXLng) {
				return getApp().showToast({
					title: '没有经纬度信息',
					icon: 'none'
				})
			}
			wx.openLocation({
				latitude: Number(this.info.TXLat), // 要去的纬度
				longitude: Number(this.info.TXLng), // 要去的经度
				name: this.info.Name,
				address: this.info.Address
			})
		},
		locConfirm() {
			wx.openSetting().then((auth) => {
				this.showConfirm = false
				if (auth.authSetting['scope.userLocation']) {
					this.navigateLocation()
				} else {
					getApp().showToast({
						title: '地理位置授权失败',
						icon: 'none'
					})
				}
			})
		},
		locate() {
			// #ifdef H5
			wx.getLocation({
				type: 'gcj02', // gcj02 返回可用于 wx.openLocation 的坐标
				altitude: true, // 传入 true 会返回高度信息
				success: (res1) => {
					this.navigateLocation()
				},
				fail: () => {
					this.showConfirm = true
				},
				complete: () => {}
			})
			// #endif
			// #ifndef H5
			wx.getSetting({
				success(res) {
					if (!res.authSetting['scope.userLocation']) {
						wx.getLocation({
							type: 'gcj02', // gcj02 返回可用于 wx.openLocation 的坐标
							altitude: true, // 传入 true 会返回高度信息
							success: (res1) => {
								this.navigateLocation()
							},
							fail: () => {
								this.showConfirm = true
							},
							complete: () => {}
						})
					} else {
						this.showConfirm = false
						this.navigateLocation()
					}
				},
				fail() {
					getApp().showToast({
						title: '地理位置授权异常',
						icon: 'none'
					})
				}
			})
			// #endif
		},
		chooseLocation() {
			return new Promise((resolve, reject) => {
				// #ifdef H5
				wx.chooseLocation({
					success(res) {
						resolve(res);
					},
					fail(err) {
						reject(err)
					}
				})
				// #endif
				// #ifndef H5
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							wx.authorize({
								scope: 'scope.userLocation',
								success() {
									wx.chooseLocation({
										success(res) {
											resolve(res);
										},
										fail(err) {
											reject(err)
										}
									})
								},
								fail() {
									wx.showModal({
										content: '获取地理位置需要开启授权，是否开启？',
										confirmText: "确认",
										cancelText: "取消",
										success: function(res) {
											if (res.confirm) {
												wx.openSetting({
													success: (
														res
													) => {} //打开设置面板
												})
											} else {
												console.log('用户点击取消')
											}
										}
									});
								}
							})
						} else {
							wx.chooseLocation({
								success(res) {
									resolve(res);
								},
								fail(err) {
									reject(err)
								}
							})
						}
					},
					fail() {
						getApp().showToast({
							title: '地理位置授权异常',
							icon: 'none'
						})
					}
				})
				// #endif
			})
		},
		chooseAddress() {
			return new Promise((resolve, reject) => {
				wx.getSetting({
					success(res) {
						if (res.authSetting['scope.address']) {
							// 已经授权过获取地址
							wx.chooseAddress({
								success(res) {
									resolve(res);
								},
								fail(err) {
									reject(err);
								}
							});
						} else {
							wx.authorize({
								scope: 'scope.address',
								success() {
									wx.chooseLocation({
										success(res) {
											resolve(res);
										},
										fail(err) {
											reject(err)
										}
									})
								},
								fail() {
									wx.showModal({
										content: '获取微信地址需要开启授权，是否开启？',
										confirmText: "确认",
										cancelText: "取消",
										success: function(res) {
											if (res.confirm) {
												wx.openSetting({
													success: (
														res
													) => {} //打开设置面板
												})
											} else {
												console.log('用户点击取消')
											}
										}
									});
								}
							})
						}
					},
					fail() {
						getApp().showToast({
							title: '微信地址授权异常',
							icon: 'none'
						})
					}
				});
			});
		},
	}
}


export const newRecordMixin = {
	data() {
		return {
			ExtendParam: {},
			sum: '',
			form: {
				StartTime: '',
				EndTime: '',
				Page: 1,
				PageSize: 20
			},
			StartTime: '',
			EndTime: '',
			finished: false,
			list: []
		}
	},
	methods: {
		// 重置
		reset(i) {
			if (i == 1) {
				this.form.StartTime = ''
				this.StartTime = ''
			} else {
				this.form.EndTime = ''
				this.EndTime = ''
			}
		},
		// 搜索
		saveTime() {
			if (this.StartTime != '' || this.EndTime != '') {
				if (this.StartTime == '') {
					getApp().showToast('请选择开始时间')
					return false
				}
				if (this.EndTime == '') {
					getApp().showToast('请选择结束时间')
					return false
				}
				const nowStart = new Date(this.StartTime).getTime()
				const nowEnd = new Date(this.EndTime).getTime()
				if (nowStart > nowEnd) {
					getApp().showToast('结束时间必须大于等于开始时间')
					return false
				}
				this.form.StartTime = this.StartTime + ' 00:00:00'
				this.form.EndTime = this.EndTime + ' 23:59:59'
			}
			// this.resetData()
			// this.getData()
		},
		changeTime1(e) {
			this.StartTime = e.detail.value
		},
		changeTime2(e) {
			this.EndTime = e.detail.value
		}
	}
}


export const payInfo = {
	data() {
		return {
			
		}
	},
	methods: {
		oncePay(corderid,amout,isPiont) {
			if(isPiont==0){
				
				let para = {
					corderid: corderid,
					paymoney: amout,
					payno:'',
				}
				GetPointOrderPay(para)
				.then(res=>{
					if(res.code==20000){
						getApp().showToast('支付成功')
					}
				})
			}else{
				wx.login().then((d) => {
					let para = {
						appid: WX_APPID,
						code: d.code,
						corderid: corderid,
						paymoney: amout,
					}
					GetWeiXinPay(para).then(result => {
						console.log("===result=" + result);
				
						if (result.code == 20000) {
							let payinfoStr = result.data.payinfo;
							console.log("payinfoStr------》" + payinfoStr);
							let payinfo = JSON.parse(payinfoStr);
				
							wx.requestPayment({
								"timeStamp": payinfo.timeStamp,
								"nonceStr": payinfo.nonceStr,
								"package": payinfo.package,
								"signType": payinfo.signType,
								"paySign": payinfo.paySign,
								"success": function(res) {
									getApp().showToast('支付成功')
				
								},
								"fail": function(res) {
				
								},
								"complete": function(res) {
				
								}
							})
				
						}
					})
				});
			}
		}
	}
}



export const saveImgMixin = {
	data() {
		return {
			shareImg: '', // 用于保存到相册的图片
			canSaveToAlbum: true,
			isSaving: false,
			ios: false,
			isIPhoneX: false
		}
	},
	methods: {
		downloadImg(t) {
			let u = !/^http(s)?/.test(t) ? `https:${t}` : t;
			return new Promise((resolve, reject) => {
				console.log('下载图片：', u);
				wx.downloadFile({
					url: u,
					// header: {
					// 	'content-type': 'image/jpeg',
					// },
					success(res) {
						resolve(res.tempFilePath)
					},
					fail(err) {},
					complate(d) {
						console.log('下载图片完成：', u, d);
					}
				})
			})
		},
		getImgInfo(t) {
			return new Promise((resolve, reject) => {
				wx.getImageInfo({
					src: t,
					success(res) {
						console.log(res)
						resolve(res)
					},
					fail(err) {
						console.log(err)
					}
				})
			})
		},
		drawText(ctx, txt, x, y, w, lh = 42) {
			let {
				row
			} = this.calcTxtLine(ctx, txt, x, y, w)
			for (let b = 0; b < row.length; b++) {
				ctx.fillText(row[b], x, y + (b + 1) * lh) // 设置字体行高
			}
		},
		calcTxtHeight(ctx, txt, x, y, w, fs, lh = 42) {
			let {
				row
			} = this.calcTxtLine(ctx, txt, x, y, w)
			let h = 0
			for (let b = 0; b < row.length; b++) {
				h += b === 0 ? fs : lh
			}
			return h
		},
		calcTxtWidth(ctx, txt, x, y, w) {
			let {
				row
			} = this.calcTxtLine(ctx, txt, x, y, w)
			return row.length > 1 ? w : ctx.measureText(txt).width
		},
		calcTxtLine(ctx, txt, x, y, w) {
			// ctx：canvas对象，txt：绘制的文字，x,y:文字坐标，w：文字最大宽度
			let chr = txt && txt.split('')
			let temp = ''
			let row = []

			for (let a = 0; a < chr.length; a++) {
				if (
					ctx.measureText(temp).width < w &&
					ctx.measureText(temp + chr[a]).width <= w
				) {
					temp += chr[a]
				} else {
					row.push(temp)
					temp = chr[a]
				}
			}
			row.push(temp)
			return {
				row
			}
		},
		fillRoundRect(ctx, x, y, width, height, radius, color = '#ffffff') {
			// 绘制填充色圆角矩形 左上角坐标 矩形宽高 圆角
			if (2 * radius > width || 2 * radius > height) {
				return false
			}
			ctx.save()
			ctx.translate(x, y)
			// 绘制圆角矩形的各个边
			this.drawRoundRectPath(ctx, width, height, radius)
			ctx.fillStyle = color
			ctx.fill()
			ctx.restore()
		},
		drawRoundRectPath(ctx, width, height, radius) {
			ctx.beginPath()
			ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2)
			ctx.lineTo(radius, height)
			ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI)
			ctx.lineTo(0, radius)
			ctx.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2)
			ctx.lineTo(width - radius, 0)
			ctx.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2)
			ctx.lineTo(width, height - radius)
			ctx.closePath()
		},
		roundrectImg(ctx, img, x, y, w, h, r) {
			ctx.beginPath()
			ctx.save()
			ctx.setLineWidth(1)
			ctx.moveTo(x + r, y)
			ctx.lineTo(x + w - r, y)
			ctx.arcTo(x + w, y, x + w, y + r, r)
			ctx.lineTo(x + w, y + h - r)
			ctx.arcTo(x + w, y + h, x + w - r, y + h, r)
			ctx.lineTo(x + r, y + h)
			ctx.arcTo(x, y + h, x, y + h - r, r)
			ctx.lineTo(x, y + r)
			ctx.arcTo(x, y, x + r, y, r)
			ctx.stroke()
			ctx.clip()
			ctx.drawImage(img, x, y, w, h)
			ctx.restore()
			ctx.closePath()
		},
		saveToAlbum() {
			let vm = this;
			if (!vm.shareImg) {
				console.log(vm.shareImg);
				getApp().showToast('图片还没准备好，请稍后');
				return;
			}
			// #ifdef H5
			// h5端下载图片
			let oA = document.createElement("a");
			oA.download = '我的推广码'; // 设置下载的文件名
			oA.href = vm.shareImg;
			document.body.appendChild(oA);
			oA.click();
			oA.remove(); // 下载之后把创建的元素删除
			return;
			// #endif
			if (this.isSaving) return;
			this.isSaving = true;
			wx.saveImageToPhotosAlbum({
				filePath: vm.shareImg,
				success(res) {
					getApp().showToast({
						title: '图片保存成功',
						icon: 'success',
						duration: 3000
					})
					// vm.addShareNum() || '';
				},
				fail(err) {
					console.log(err)
					getApp().showToast({
						title: '图片保存失败',
						icon: 'none'
					})
				},
				complete() {
					vm.isSaving = false
				}
			})
		},
		saveImg2() {
			let vm = this
			if (!this.canSaveToAlbum) {
				wx.openSetting({
					success(res) {
						if (res.authSetting['scope.writePhotosAlbum']) {
							vm.canSaveToAlbum = true
							vm.saveToAlbum()
						}
					}
				})
			} else {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									vm.canSaveToAlbum = true
									vm.saveToAlbum()
								},
								fail() {
									vm.canSaveToAlbum = false
									wx.showModal({
										title: '相册权限',
										content: '请设置允许访问相册才能保存图片',
										showCancel: false,
										confirmColor: '#ee4400'
									})
								}
							})
						} else {
							vm.canSaveToAlbum = true
							vm.saveToAlbum()
						}
					},
					fail() {}
				})
			}
		},
		saveImg() {
			let vm = this;
			// #ifdef H5
			// h5端不需要授权
			vm.saveToAlbum()
			return;
			// #endif
			if (!this.canSaveToAlbum) {
				wx.openSetting({
					success(res) {
						if (res.authSetting['scope.writePhotosAlbum']) {
							vm.canSaveToAlbum = true
							vm.saveToAlbum()
						}
					}
				})
			} else {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									vm.canSaveToAlbum = true
									vm.saveToAlbum()
								},
								fail() {
									vm.canSaveToAlbum = false
									wx.showModal({
										title: '相册权限',
										content: '请设置允许访问相册才能保存图片',
										showCancel: false,
										confirmColor: '#ee4400'
									})
								}
							})
						} else {
							vm.canSaveToAlbum = true
							vm.saveToAlbum()
						}
					},
					fail() {}
				})
			}
		}
	}
}


// 最新订单轮播公告
export const NoticeMixin = {
	data() {
		return {
			notices: [],
			hasNotices: false, // 控制有无notices时的样式
			orders: [],
			curTime: ''
		}
	},
	methods: {
		// async fetchNotice(type) {
		// 	await this.order()
		// 	return new Promise(resolve => {
		// 		this.notices = [...this.orders]
		// 		this.hasNotices = this.notices.length ? true : false;
		// 		resolve()
		// 	})
		// },
		order() {
			return new Promise(resolve => {
				GetNewOrderList().then(res => {
						
					if(res.code==20000){
						this.orders=res.data
						resolve()
					}
				})
			})
		},
		timeFrom(t) {
			let tips = ''
			switch (true) {
				case t <= 0:
					tips = '刚刚'
					break
				case t > 0 && t < 60:
					tips = t + '秒前'
					break
				case t >= 60 && t < 3600:
					tips = parseInt(t / 60) + '分钟前'
					break
				case t >= 3600 && t < 86400:
					tips = parseInt(t / 3600) + '小时前'
					break
				case t >= 86400 && t < 30 * 86400:
					tips = parseInt(t / 86400) + '天前'
					break
				case t >= 30 * 86400 && t < 365 * 86400:
					tips = parseInt(t / (86400 * 30)) + '个月前'
					break
				case t >= 86400 * 365:
					tips = parseInt(t / (86400 * 365)) + '年前'
					break
			}
			return tips
		},
	}
}